package org.zxl.iotest.netty.protobuf.server;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.zxl.iotest.netty.protobuf.util.ClientMessageID;
import org.zxl.iotest.netty.protobuf.util.ServerMessageID;
import org.zxl.iotest.netty.protobuf.util.ZxlMsgSendUtil;

import java.util.Iterator;
import java.util.Map;

/**
 * @author zhangxiaolong
 * @date 2025-02-16 17:21
 **/
@Slf4j
public class ChannelManageThread extends Thread{
    public void run() {
        log.info("ChannelManageThread run");
        while (true) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("开始清理***********************");
            if(ClientManage.ID_CHANNEL_MAP.entrySet().size() == 0){
                log.info("没有通道，无需清理***********************");
                continue;
            }
            Iterator<Map.Entry<String, Client>> iterator = ClientManage.ID_CHANNEL_MAP.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Client> entry = iterator.next();
                Client client = entry.getValue();
                if (client != null && !client.getChannel().isActive()) {
                    iterator.remove();
                    continue;
                }
                if (System.currentTimeMillis() - client.getHeartBeatTime() > 30000) {
                    //关闭连接 30秒未收到心跳，关闭连接
                    client.getChannel().close();
                    log.info("通道被关闭***********************，channelId:"+client.getChannelId()+";clientUuid:"+client.getClientUuid());
                    continue;
                }
                if (System.currentTimeMillis() - client.getHeartBeatTime() > 20000) {
                    Channel channel = client.getChannel();
                    ZxlMsgSendUtil.sendMsg(channel, ServerMessageID.ACTIVE_CHECK, null);
                    log.info("通道存活确认***********************，channelId:"+client.getChannelId()+";clientUuid:"+client.getClientUuid());
                    continue;
                }
            }
            log.info("清理完成***********************");
        }
    }
}
